package cn.web.servlet;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/CheckCodedServlet")
public class CheckCodedServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        int width=100;
        int height=50;

        // 创建一个图片对象
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);



        // 美化图片对象
        Graphics g = image.getGraphics();  // 新建一个画笔对象
        g.setColor(Color.pink);  // 设置画笔颜色
        g.fillRect(0,0,width,height); // 设置画笔画的区域 也叫做填充区域

//        2.2画边框
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width - 1,height - 1);

        String str="ABCDEFGHIZKLMNOPQRSTUVWXYZabcdefghizklmnopqrstuvwxyz1234567890";   // 随机生成字符

        Random rand = new Random();

        for (int i = 1; i <5 ; i++) {
            int index = rand.nextInt(str.length());

            char c = str.charAt(index);

            g.drawString(c + "", width/5*i, height/2);  // 写字符串
        }



        g.setColor(Color.green);
        // 随机生成干扰线


        for (int i = 0; i <10; i++) {
            int x = rand.nextInt(width);
            int y = rand.nextInt(height);

            int x1 = rand.nextInt(width);
            int y1 = rand.nextInt(height);
            g.drawLine(x, y, x1, y1);
        }



        ImageIO.write(image,"jpg",response.getOutputStream());


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                this.doPost(request,response);
    }
}
/*
 *  1。创建一个对象，能在内存中画图（验证码图片对象）2。美化图片 3 将图片输出到页面展示
 *
 */